<template>
  <div class="owner-tree">
    <span class="del-arrow"></span>
    <el-popover ref="popover-tree" v-model.trim="popoverVisable" placement="top" visible-arrow="false" trigger="click">
      <el-input size="mini" slot="reference" v-model.trim="inputValue" @focus="handleInputFocus" :placeholder="$t('public.pickAgentTip')">
      </el-input>
      <el-tree-new
        class="a-tree"
        ref="tree"
        node-key="_id"
        height="300"
        :show-checkbox="isNotice"
        :data="optionData"
        :default-expanded-keys="defaultExpandedKeys"
        accordion
        :highlight-current="true"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick">
      </el-tree-new>
    </el-popover>
  </div>
</template>
<script>
  import { filterAllCategory } from '@/utils/customerUtils.js'
  import {deepClone} from '@/utils/m7Utils'
  import tree from '../../ui-modules/tree/src/tree.vue'
  export default {
    name: 'OwnerTreeSelect',
    components: {
      'el-tree-new': tree
    },
    data () {
      return {
        scopeNoticeArray: [],
        inputValue: '',
        defaultExpandedKeys: ['common'],
        optionData: [],
        popoverVisable: false
      }
    },
    props: {
      _scopeArray: Array,
      isNotice: Boolean,
      businessType: {
        type: String,
        default: ''
      },
      owner: {
        type: String,
        default: ''
      },
      name: {type: String, default: ''}
    },
    watch: {
      inputValue (val) {
        this.$refs.tree.filter(val)
        if (val === '') {
          this.$emit('owner-reset', this.name)
          this.expandNode()
        }
      },
      owner (curr, prev) {
        if (curr === '') {
          this.$emit('resetValue')
        } else if (curr.indexOf('myself__') > -1 && curr.indexOf('flag') > -1) { // flag 代表是全部通话里面的快捷搜索我的通话
          console.log('被执行了====================')
          let data = {label: this.$t('public.myself'), name: 'ownercom', type: 'ownercom', _id: 'myself'}
          this.handleNodeClick(data)
        }
      },
      popoverVisable (val) {
        if (val) {
          this.$refs.tree.reset()
        }
      }
    },
    methods: {
      getCheckedNodes () {
        return this.$refs.tree.getCheckedNodes()
      },
      filterNode (value, data) {
        if (!value) return true
        if (data.label || data.pinyin) return data.label.indexOf(value) !== -1 || (data.pinyin && data.pinyin.indexOf(value) !== -1)
      },
      expandNode () {
        this.$refs.tree.root.childNodes.map(childNode => {
          if (childNode.data._id === 'common') {
            childNode.expand()
          } else {
            childNode.collapse()
          }
        })
      },
      handleInputFocus () {
        if (this.inputValue) {
          this.$refs.tree.filter()
        }
        this.expandNode()
      },
      handleNodeClick (data) {
        if (!data.type) {
          return
        }
        this.popoverVisable = false
        this.inputValue = data.displayName || data.label
        data.name = this.name
        this.$emit('owner-change', data)
      },
      resetValue (value) {
        // 如果传value 给inputValue赋值
        if (value) {
          let data = this.$refs.tree.getNode(value) || {}
          this.inputValue = data.displayName || data.label
        } else {
          this.inputValue = ''
        }
      }
    },
    mounted () {
      console.log(22334455)
      if (this._scopeArray) {
        this.scopeNoticeArray = deepClone(this._scopeArray)
        this.$refs.tree.setCheckedKeys(this.scopeNoticeArray)
      }
    },
    beforeDestroy: function () {
      this.$off('resetValue', this.resetValue)
    },
    beforeMount () {
      Promise.all([
        this.$store.dispatch('getCache', { type: 'depts' }),
        this.$store.dispatch('getCache', { type: 'agents' }),
        this.$store.dispatch('getCache', { type: 'custCategorys' })
      ]).then(([depts, agents, custCategorysCache]) => {
        let optionData = []
        let custCategorys = filterAllCategory()
        let emptyOption = {
          _id: '',
          label: this.$t('public.all'),
          type: 'ownercom'
        }
        let commonOption = {
          _id: 'common',
          label: this.$t('public.common'),
          children: [
            {_id: 'myself', type: 'ownercom', label: this.$t('public.myself')},
            {_id: 'my-subordinates', type: 'ownercom', label: this.$t('public.myAndMylower')},
            {_id: 'my-department', type: 'ownercom', label: this.$t('public.ownerDept')},
            {_id: 'my-subordinates-dept', type: 'ownercom', label: this.$t('public.ownerAndMyLowerDept')}
          ]
        }
        let noOwner = {_id: 'NA', type: 'owner', label: this.$t('customer.noOwner')}
        let _custCategorys = custCategorys.map(category => ({_id: category._id, type: 'owner', label: category.displayName, displayName: category.cName}))
        let _agents = agents.map(agent => ({_id: agent._id, type: 'owner', label: `${agent.displayName}[${agent.exten}]`, displayName: agent.displayName, pinyin: agent.pinyin}))
        let customerOwners = []
        let otherOwners
        if (this.isNotice) {
          customerOwners = [..._custCategorys, ..._agents]
          otherOwners = [..._agents]
        } else {
          customerOwners = [noOwner, ..._custCategorys, ..._agents]
          otherOwners = [noOwner, ..._agents]
        }
        let ownerOption = {
          _id: 'owner',
          label: this.businessType === 'customer' ? this.$t('customer.customerOwner') : this.$t('customer.customerWorker'),
          children: this.businessType === 'customer' ? customerOwners : otherOwners
        }
        let _depts = depts.filter(dept => dept.pId !== '')
        _depts = _depts.map(dept => ({ _id: dept._id, type: 'ownerdep', label: dept.name }))
        let deptOption = {
          _id: 'dept',
          label: this.$t('customer.customerDept'),
          children: _depts
        }
        if (this.isNotice) {
          optionData.push(...[emptyOption, ownerOption, deptOption])
        } else {
          optionData.push(...[emptyOption, commonOption, ownerOption, deptOption])
        }
        this.optionData = optionData
        this.$emit('tree-data', this.optionData,this.scopeNoticeArray)
        this.$on('resetValue', this.resetValue)
      })
    }
  }
</script>
<style lang="stylus" scoped>
.a-tree
  max-height 300px
  min-width 190px
  overflow-y auto
</style>
